package com.runvp.common.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.Payment;
import com.huifu.adapay.model.Refund;
import com.runvp.common.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;


/**
 * @author jane.zhao
 */
@Slf4j
public class PaymentUtil {

    /**
     * 执行一个支付交易
     *
     * @return 创建的支付对象
     * @throws Exception 异常
     */
    public static Map<String, Object> executePayment(String app_id,OrderCreateModel model) throws Exception {
        log.info("=======execute payment begin=======");
        //创建支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/index.html
        Map<String, Object> paymentParams = new HashMap<>(10);

        paymentParams.put("adapay_connection_request_timeout", 5000);
        paymentParams.put("adapay_connect_timeout", 5000);
        paymentParams.put("adapay_socket_timeout", 5000);
        paymentParams.put("app_id", app_id);
        paymentParams.put("order_no", "jsdk_payment_" + System.currentTimeMillis());
        paymentParams.put("pay_channel", "wx_lite");
        paymentParams.put("pay_amt", model.getPayAmt());
        paymentParams.put("goods_title", model.getGoodsTitle());
        paymentParams.put("goods_desc", model.getGoodsDesc());
        paymentParams.put("callback_url", "http://wash.runlaiwangluo.com/app/pay/callback");

        Map<String, Object> expendParams = new HashMap<>(2);
        expendParams.put("open_id", model.getOpenId());
//        expendParams.put("is_raw", "1");
        expendParams.put("callback_url", "http://wash.runlaiwangluo.com/app/pay/callback");
//        expendParams.put("limit_pay", "1");
        paymentParams.put("expend", expendParams);
        //调用sdk方法，创建支付，得到支付对象
        Map<String, Object> payment = new HashMap<>();
        try {
            log.info("支付交易，请求参数：" + JSON.toJSONString(paymentParams));
            payment = Payment.create(paymentParams);

        } catch (BaseAdaPayException e) {
            e.printStackTrace();
        }
        log.info("支付交易，返回参数：" + JSON.toJSONString(payment));
        log.info("=======execute payment end=======");
        return payment;
    }

    /**
     * 退款
     * @param model
     * @return map -{"payment_order_no":"jsdk_payment_1685026696863","created_time":"1685026762000","reason":"","refund_amt":"3.60","notify_url":"","payment_id":"002212023052522581710507822928329609216","prod_mode":"true","channel_no":"2023052521R2230t","succeed_time":"1685026762000","id":"0022120230525225921980507823199148744704","app_id":"app_55f5c01c-b593-4176-98a9-d7ddc3d97021","refund_order_no":"jsdk_payment_1685026696863","fee_amt":"0.02","object":"refund","status":"pending"}
     */
    public static Map<String, Object> refund(OrderRefundModel model){
        try{
            log.info("退款参数:{}", JSONObject.toJSONString(model));
            Map<String, Object> refundParams = new HashMap<String, Object>();
            refundParams.put("refund_amt", model.getRefund_amt());
            refundParams.put("refund_order_no", model.getRefund_order_no());
            Map<String, Object> response = Refund.create(model.getId(), refundParams);
            log.info("退款结果:{}", JSONObject.toJSONString(response));
            return response;
        }catch (Exception e){
            e.printStackTrace();
            log.error("订单【{}】退款失败",model.getRefund_order_no(),e);
            throw new BaseException("退款失败:"+e.getMessage());
        }
    }

    /**
     * 退款查询
     * @param model
     * @return Map<String, Object> -{"prod_mode":"true","status":"succeeded","refunds":[{"payment_id":"002212023052522581710507822928329609216","refund_amt":"3.60","refund_id":"0022120230525225921980507823199148744704","refund_order_no":"jsdk_payment_1685026696863","trans_status":"S","fee_amt":"0.02"}]}
     */
    public static Map<String, Object> refundQuery(OrderRefundModel model){
        try{
            Map<String, Object> refundParams = new HashMap<String, Object>();
            refundParams.put("refund_order_no", model.getRefund_order_no());
            Map<String, Object> response = Refund.query(refundParams);
            log.info("退款状态查询:{}", JSONObject.toJSONString(response));
            return response;
        }catch (Exception e){
            e.printStackTrace();
            log.error("订单【{}】退款失败error:{}",model.getRefund_order_no(),e.getMessage());
            throw new BaseException("退款失败:"+e.getMessage());
        }
    }
    /**
     * 执行一个二维码支付交易
     *
     * @return 创建的支付对象
     * @throws Exception 异常
     */
    public static Map<String, Object> executeQRPayment(String app_id,OrderCreateModel model) throws Exception {
        log.info("=======execute qr payment begin=======");
        //创建支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/index.html
        Map<String, Object> paymentParams = new HashMap<>(10);

        paymentParams.put("adapay_connection_request_timeout", 5000);
        paymentParams.put("adapay_connect_timeout", 5000);
        paymentParams.put("adapay_socket_timeout", 5000);
        paymentParams.put("adapay_func_code", "qrPrePay.qrPreOrder");
        paymentParams.put("app_id", app_id);
        paymentParams.put("pay_channel", "alipay_qr");

        paymentParams.put("order_no", model.getOrderNo());
        paymentParams.put("pay_amt", model.getPayAmt());
        paymentParams.put("goods_title", model.getGoodsTitle());
        paymentParams.put("goods_desc", model.getGoodsDesc());
        paymentParams.put("callback_url", "http://wash.runlaiwangluo.com/app/pay/callback");
        paymentParams.put("expend", "{}");

        //调用sdk方法，创建支付，得到支付对象
        Map<String, Object> payment = new HashMap<>();
        try {
            log.info("QR支付交易，请求参数：" + JSON.toJSONString(paymentParams));
            payment = Payment.create(paymentParams);

        } catch (BaseAdaPayException e) {
            e.printStackTrace();
        }
        log.info("QR支付交易，返回参数：" + JSON.toJSONString(payment));
        log.info("=======execute payment end=======");
        return payment;
    }
}
